from selenium.webdriver.support.expected_conditions import staleness_of
from .PageElement import *
from robot.api import logger
# from selenium.common.exceptions import TimeoutException


class WaitPageLoad:
    """
    在with包裹的情况下,判断动作的执行前后有没有loading 或者期望某个element元素发生变化再结束整个触发事件
    默认情况下不输入参数的时候,只判断当前有没有loading条
    """

    def __init__(self, browser, selector_str: str = None, selector_type: str = None, timeout=None, interval=0,
                 times=None, duration=None, is_exit_check=False):
        '''
        初始化
        :param browser: 浏览器驱动
        :param selector_str: 选择元素
        :param selector_type: 元素选择器的类型
        :param timeout: 等待blockUI多少秒，小于或等于0为一直等待
        :param interval: 当有多个blockUI出现时，设置的没有blockUI出现的间隔
        :param duration: 要持续等待多少秒时间没有block UI，针对刚登录后，密集出现block UI的情况
        :param is_exit_check: with退出时，是否也要检查waiting Block UI 消息
        '''
        self.browser = browser
        self.times = int(times) if times else times
        self.timeout = timeout or FwVariables.get_wait_time_out()
        self._selector_str = selector_str
        self._selector_type = selector_type
        self.interval = int(interval)  # 默认0s检查一次
        self._duration = duration
        self._is_exit_check = is_exit_check
        if self._selector_str is None and self._selector_type is None:
            self._selector_str = 'blockUI'
            self._selector_type = Selector.CLASS_NAME
            self._break_flag = True
        else:
            self._break_flag = False

    # 保留，怕改崩了
    def __enter__(self):
        '''
        增加规避连续多个blockUI
        :return:
        '''
        if self.times:
            for loop in range(self.times):
                logger.info("第{}次循环检测blockUI".format(int(loop)+1))
                if not self._check_blockUI():
                    if self._is_present_blockUI():
                        continue
                    else:
                        logger.info('未发现BlockUI，且等待{}s后，blockUI也未出现'.format(self.interval))
                        break
                else:
                    time.sleep(0.5)
        else:
            self._check_blockUI()

    # 保留，怕改崩了
    def __exit__(self, *_):
        if self._break_flag is False:
            WebDriverWait(self.browser, self.timeout).until(staleness_of(self.old_page))
        else:
            old_pages = PageElement(self.browser, self._selector_str, self._selector_type)._get_web_elements()
            if len(old_pages) > 0:
                try:
                    self.old_page = WebDriverWait(self.browser, self.timeout).until(
                        EC.presence_of_element_located((Selector.MAP[self._selector_type], self._selector_str)))
                    display_flag = self.old_page.value_of_css_property("display")
                    if "none" in display_flag.lower():
                        self.old_page = None
                        return
                except Exception:
                    pass
                old_pages = PageElement(self.browser, self._selector_str, self._selector_type)._get_web_elements()
                if len(old_pages) > 0:
                    self.old_page = old_pages[0]
                    try:
                        WebDriverWait(self.browser, self.timeout).until(staleness_of(self.old_page))
                        # WebDriverWait(self.browser, 10).until(staleness_of(self.old_page))
                    except TimeoutException as e:
                        old_pages = PageElement(self.browser, self._selector_str, self._selector_type)._get_web_elements()
                        if len(old_pages) <= 0:
                            return
                        self.old_page = old_pages[0]
                        display_flag = self.old_page.value_of_css_property("display")
                        if "none" in display_flag.lower():
                            self.old_page = None
                            return
                        raise Exception(e, 'Is too lang to wait UI to disappear.')
            else:
                return

    # 重写方法，之前暂保留，怕改崩了
    def _check_blockUI(self):
        old_pages = PageElement(self.browser, self._selector_str, self._selector_type)._get_web_elements()
        if self._break_flag is False:
            self.old_page = old_pages[0]
            return
        else:
            if len(old_pages) > 0:
                logger.info("检测到BlockUI，并等待该BlockUI元素消失")
                try:
                    self.old_page = WebDriverWait(self.browser, self.timeout).until(
                        EC.presence_of_element_located((Selector.MAP[self._selector_type], self._selector_str)))
                    # self.old_page = old_pages[0]
                    display_flag = self.old_page.value_of_css_property("display")
                    if "none" in display_flag.lower():
                        self.old_page = None
                        return
                except Exception:
                    pass
                old_pages = PageElement(self.browser, self._selector_str, self._selector_type)._get_web_elements()
                if len(old_pages) > 0:
                    self.old_page = old_pages[0]
                    try:
                        return WebDriverWait(self.browser, self.timeout).until(staleness_of(self.old_page))
                        # return WebDriverWait(self.browser, 10).until(staleness_of(self.old_page))
                    except TimeoutException as e:
                        old_pages = PageElement(self.browser, self._selector_str, self._selector_type)._get_web_elements()
                        if len(old_pages) <= 0:
                            return
                        self.old_page = old_pages[0]
                        display_flag = self.old_page.value_of_css_property("display")
                        if "none" in display_flag.lower():
                            self.old_page = None
                            return
                        raise Exception(e, 'Is too lang to wait UI to disappear.')
            else:
                self.old_page = None
                return

    def wait_blockUI_for_a_moment(self, wait_time):
        try:
            PageElement(self.browser, self._selector_str, self._selector_type).wait_element_presence(
                timeout=wait_time)
        except:
            return False
        else:
            return True

    def _is_present_blockUI(self):
        try:
            PageElement(self.browser, self._selector_str, self._selector_type).wait_element_presence(
                timeout=self.interval)
        except:
            return False
        else:
            return True
